<script setup lang="ts">
// 扩展Window接口，声明initTAC方法
import useUserStore from '@/store/modules/user'
import { FormControl, FormField, FormItem, FormMessage } from '@/ui/shadcn/ui/form'
import { sm2 } from '@/utils/sm2'
import { toTypedSchema } from '@vee-validate/zod'
import { ElMessage } from 'element-plus'
import { useForm } from 'vee-validate'
import * as z from 'zod'

declare global {
  interface Window {
    initTAC: (path: string, config: any, style: any) => Promise<any>
  }
}

defineOptions({
  name: 'LoginForm',
})

const props = defineProps<{
  username?: string
}>()

const emits = defineEmits<{
  onLogin: [username?: string]
  onRegister: [username?: string]
  onResetPassword: [username?: string]
}>()

const userStore = useUserStore()

// const title = import.meta.env.VITE_APP_TITLE
const loading = ref(false)

const loginTabs = ref([{
  label: '账号密码登录',
  value: 'default',
}])

// 登录方式，default 账号密码登录，passkey Passkey 登录
const type = ref<'default' | 'passkey'>('default')

const form = useForm({
  validationSchema: toTypedSchema(z.object({
    username: z.string().min(1, '请输入用户名'),
    password: z.string().min(1, '请输入密码'),
    remember: z.boolean(),
  })),
  initialValues: {
    username: props.username ?? localStorage.getItem('login_username') ?? 'easyadmin',
    password: '123456',
    remember: !!localStorage.getItem('login_username'),
  },
})

function login(values) {
  loading.value = true
  values.password = `04${sm2.doEncrypt(values.password, import.meta.env.VITE_APP_PUBLIC_KEY)}`
  userStore.login(values).then(() => {
    if (values.remember) {
      localStorage.setItem('login_username', values.username)
    }
    else {
      localStorage.removeItem('login_username')
    }
    emits('onLogin', values.username)
  }).catch((err) => {
    console.log('err', err)
    if (err.status === 401) {
      ElMessage.error(err.data.msg)
    }
  }).finally(() => {
    loading.value = false
  })
}

const onSubmit = form.handleSubmit((values) => {
  // config 对象为TAC验证码的一些配置和验证的回调
  const config = {
    // 生成接口 (必选项,必须配置, 要符合tianai-captcha默认验证码生成接口规范)
    requestCaptchaDataUrl: `${import.meta.env.VITE_APP_API_BASEURL}/admin/captcha/generate`,
    // 验证接口 (必选项,必须配置, 要符合tianai-captcha默认验证码校验接口规范)
    validCaptchaUrl: `${import.meta.env.VITE_APP_API_BASEURL}/admin/captcha/check`,
    // 验证码绑定的div块 (必选项,必须配置)
    bindEl: '#captcha-box',
    // 验证成功回调函数(必选项,必须配置)
    validSuccess: (res: any, c: any, tac: any) => {
      // 销毁验证码服务
      tac.destroyWindow()
      console.log('验证成功，后端返回的数据为', res, c)
      // 调用具体的login方法
      login(values)
    },
    // 验证失败的回调函数(可忽略，如果不自定义 validFail 方法时，会使用默认的)
    validFail: (res: any, c: any, tac: any) => {
      console.log('验证码验证失败回调...', res, c)
      // 验证失败后重新拉取验证码
      tac.reloadCaptcha()
    },
    // 刷新按钮回调事件
    btnRefreshFun: (tac: any) => {
      console.log('刷新按钮触发事件...')
      tac.reloadCaptcha()
    },
    // 关闭按钮回调事件
    btnCloseFun: (tac: any) => {
      console.log('关闭按钮触发事件...')
      tac.destroyWindow()
    },
  }
  // 一些样式配置， 可不传
  const style = {
    logoUrl: null, // 去除logo
    // logoUrl: "/xx/xx/xxx.png" // 替换成自定义的logo
  }
  // 参数1 为 tac文件是目录地址， 目录里包含 tac的js和css等文件
  // 参数2 为 tac验证码相关配置
  // 参数3 为 tac窗口一些样式配置
  window.initTAC('./captcha/tac', config, style).then((tac) => {
    tac.init() // 调用init则显示验证码
  }).catch((e) => {
    console.log('初始化tac失败', e)
  })
})


</script>

<template>
  <div class="min-h-500px w-full flex-col-stretch-center p-12">
    <div class="mb-6 space-y-2">
      <h3 class="text-4xl color-[var(--el-text-color-primary)] font-bold">
        欢迎使用 👋🏻
      </h3>
      <p class="text-sm text-muted-foreground lg:text-base">
        EasyAdmin 管理系统
      </p>
    </div>
    <div class="mb-4">
      <FaTabs
        v-model="type" :list="loginTabs" class="inline-flex"
      />
    </div>
    <div v-show="type === 'default'">
      <form @submit="onSubmit">
        <FormField v-slot="{ componentField, errors }" name="username">
          <FormItem class="relative pb-6 space-y-0">
            <FormControl>
              <FaInput type="text" placeholder="请输入用户名" class="w-full" :class="errors.length && 'border-destructive'" v-bind="componentField" />
            </FormControl>
            <Transition enter-active-class="transition-opacity" enter-from-class="opacity-0" leave-active-class="transition-opacity" leave-to-class="opacity-0">
              <FormMessage class="absolute bottom-1 text-xs" />
            </Transition>
          </FormItem>
        </FormField>
        <FormField v-slot="{ componentField, errors }" name="password">
          <FormItem class="relative pb-6 space-y-0">
            <FormControl>
              <FaInput type="password" placeholder="请输入密码" class="w-full" :class="errors.length && 'border-destructive'" v-bind="componentField" />
            </FormControl>
            <Transition enter-active-class="transition-opacity" enter-from-class="opacity-0" leave-active-class="transition-opacity" leave-to-class="opacity-0">
              <FormMessage class="absolute bottom-1 text-xs" />
            </Transition>
          </FormItem>
        </FormField>
        <div class="mb-4 mt4 flex-center-between">
          <div class="flex-center-start">
            <FormField v-slot="{ componentField }" type="checkbox" name="remember">
              <FormItem>
                <FormControl>
                  <FaCheckbox v-bind="componentField">
                    记住我
                  </FaCheckbox>
                </FormControl>
              </FormItem>
            </FormField>
          </div>
          <FaButton variant="link" class="h-auto p-0" type="button" @click="emits('onResetPassword', form.values.username)">
            忘记密码了?
          </FaButton>
        </div>
        <div id="captcha-box"></div>
        <FaButton :loading="loading" size="lg" class="w-full" type="submit">
          登录
        </FaButton>
        <!-- <div class="mt-4 flex-center gap-2 text-sm">
          <span class="text-secondary-foreground op-50">还没有帐号?</span>
          <FaButton variant="link" class="h-auto p-0" type="button" @click="emits('onRegister', form.values.username)">
            注册新帐号
          </FaButton>
        </div> -->
      </form>
    </div>
  </div>
</template>

<style lang="css" scoped>
#captcha-box {
  position: absolute;
  right: 50px;
  bottom: 120px;
}

.login-code {
  float: left;
  width: 33%;
  height: 40px;
  margin-left: 20px;

  img {
    vertical-align: middle;
    cursor: pointer;
  }
}
</style>
